<template>
  <div style="padding: 10px; display: flex; flex-direction: column; height: 100%">
    <el-form ref="cameraMonitorPlanFormRef" :model="form" :rules="rules" label-width="80px" style="height: calc(100% - 50px); display: flex; flex-direction: column">
      <el-form-item label="预案名称" prop="monitorPlanName">
        <el-input v-model="form.monitorPlanName" maxlength="20" placeholder="请输入监控预案名称" />
      </el-form-item>
      <el-form-item label="是否轮播" prop="whetherCarousel">
        <el-radio-group v-model="form.whetherCarousel">
          <el-radio :value="1">是</el-radio>
          <el-radio :value="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.whetherCarousel == 1" label="轮播时间" prop="carouselTime">
        <el-input-number v-model="form.carouselTime" :mix="1" :max="999" placeholder="请输入轮播时间" />&nbsp;秒
      </el-form-item>
      <el-form-item label="选择视频" prop="equipmentIds" class="select-camera-form-item">
        <div style="height: 100%; width: 48%; display: flex; flex-direction: column">
          <div style="margin-bottom: 20px; font-size: 18px">所有设备</div>
          <el-table ref="multipleTableRef" v-loading="cameraLoading" :data="cameraInfoList" border style="flex: 1" @selection-change="tableSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="设备名称" align="center" prop="equipmentName" width="150px" show-overflow-tooltip />
            <el-table-column label="设备识别码" align="center" prop="deviceId" show-overflow-tooltip />
          </el-table>
          <div style="width: 100%; display: flex; justify-content: flex-end; align-items: center">
            <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" size="small" layout="total, prev, pager, next" @pagination="getCameraList" />
          </div>
        </div>

        <div style="height: 100%; width: 48%; display: flex; flex-direction: column">
          <div style="margin-bottom: 20px; font-size: 18px">已选设备</div>
          <el-table :data="selectedEquipmentList" border style="flex: 1; margin-bottom: 35px">
            <el-table-column label="设备名称" align="center" prop="equipmentName" width="150px" show-overflow-tooltip />
            <el-table-column label="设备识别码" align="center" prop="deviceId" show-overflow-tooltip />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
    </el-form>

    <!-- eslint-disable prettier/prettier -->
    <div style="height: 50px; display: flex; justify-content: center; align-items: center;">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="emit('close')">取 消</el-button>
    </div>
  </div>
</template>

<!-- eslint-disable prettier/prettier -->
<script setup name="cameraMonitorPlan" lang="ts">
import { updatecameraMonitorPlan, getcameraMonitorPlan } from '@/api/security/video-monitor/camera-monitor-plan';
import { cameraInfoVO } from '@/api/security/camera/camera-info/types';
import request from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const cameraInfoList = ref<cameraInfoVO[]>([]);
const buttonLoading = ref(false);
const cameraLoading = ref(false);
const cameraMonitorPlanFormRef = ref<ElFormInstance>();

const data = reactive({
  form: {
    cameraMonitorPlanId: undefined,
    remark: undefined,
    monitorPlanName: undefined,
    whetherCarousel: undefined,
    carouselTime: undefined,
    equipmentId: []
  },
  rules: {
    cameraMonitorPlanId: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    monitorPlanName: [{ required: true, message: '监控预案名称不能为空', trigger: 'blur' }],
    equipmentIds: [{ required: true, message: '监控不能为空', trigger: 'blur' }],
    whetherCarousel: [{ required: true, message: '是否轮播不能为空', trigger: 'blur' }],
    carouselTime: [{ required: true, message: '轮播时间不能为空', trigger: 'blur' }]
  }
});

const { form, rules } = toRefs(data);
const selectedEquipmentList = ref([]);
const multipleTableRef = ref<any>();
const lockTableSelectionChange = ref(false);
const total = ref(0);
const queryParams = ref({ pageNum: 1, pageSize: 20 });

const props = defineProps({
  cameraMonitorPlanId: {
    type: String,
    default: undefined,
    required: true
  }
});

const emit = defineEmits(['close', 'success']);

/**
 * 获取监控预案信息
 */
const getInfo = async () => {
  proxy?.$modal.loading('加载中...')
  const res = await getcameraMonitorPlan(props.cameraMonitorPlanId).finally(() => { proxy?.$modal.closeLoading() })
  Object.assign(form.value, res.data);

  console.log('获取监控预案信息：', res)
};

/** 查询摄像头信息列表 */
const getCameraList = async () => {
  cameraLoading.value = true;
  lockTableSelectionChange.value = true;
  request({
    url: '/equipment/equipment-info/list',
    method: 'get',
    params: { dataSource: 2, ...queryParams.value }
  }).then((res) => {
    cameraInfoList.value = res.rows;
    total.value = res.total;

    console.log('获取摄像头信息列表：', res)

    // 选中已选设备
    nextTick(() => {
      selectedEquipmentList.value.forEach(selectedCamera => {
        cameraInfoList.value.forEach(camera => {
          if (camera.equipmentId == selectedCamera.equipmentId) {
            multipleTableRef.value!.toggleRowSelection(camera, true, false)
          }
        });
      })

      lockTableSelectionChange.value = false;
    })
  }).finally(() => { cameraLoading.value = false; });
};

/**
 * 获取选择的监控预案设备
 */
const getSelectedCameraList = ()=> {
  request({
    url: '/camera/camera-monitor-plan-camera/list',
    method: 'get',
    params: { planId: props.cameraMonitorPlanId }
  }).then((res) => {
    console.log('获取选择的监控预案设备：', res)

    form.value.equipmentIds = res.rows.map((item) => { return item.equipmentId; })

    res.rows.forEach(selectedCamera => {
      selectedEquipmentList.value.push(selectedCamera);

      cameraInfoList.value.forEach(camera => {
        if (camera.equipmentId == selectedCamera.equipmentId) {
          multipleTableRef.value!.toggleRowSelection(camera, true, false)
        }
      });
    })
  }).finally(()=> { })
}

/** 多选框选中数据 */
const tableSelectionChange = (selection) => {
  if (lockTableSelectionChange.value == false) {
    selection.forEach(item => {
      // 如果勾选设备不在已选设备列表中，则添加到已选设备列表
      let hasSelectedEquipment = selectedEquipmentList.value.find((selectedItem) => { return selectedItem.equipmentId == item.equipmentId; })
      if (hasSelectedEquipment == null) {
        selectedEquipmentList.value.push(item);
      }
    })

    // 获取当前页面没有选中的设备，并将其从已选设备列表中移除
    let currPageNotSelectedEquipmentList = cameraInfoList.value.filter(equipment => { return !selection.includes(equipment) })
    currPageNotSelectedEquipmentList.forEach(currPageNotSelectedEquipment => {
      let currPageNotSelectedEquipmentIndex = selectedEquipmentList.value.findIndex((selectedItem) => { return selectedItem.equipmentId == currPageNotSelectedEquipment.equipmentId; })
      if (currPageNotSelectedEquipmentIndex != -1) {
        selectedEquipmentList.value.splice(currPageNotSelectedEquipmentIndex, 1);
      }
    })
  }

  form.value.equipmentIds = selectedEquipmentList.value.map((item) => { return item.equipmentId; })
};

/** 删除按钮操作 */
const handleDelete = async (row) => {
  await proxy?.$modal.confirm('是否确认删除设备信息编号为"' + row.equipmentId + '"的数据项？');

  selectedEquipmentList.value.splice(selectedEquipmentList.value.indexOf(row), 1);

  cameraInfoList.value.forEach(equipment => {
    if (equipment.equipmentId == row.equipmentId) {
      multipleTableRef.value!.toggleRowSelection(equipment, false, false)
    }
  });

  form.value.equipmentIds = selectedEquipmentList.value.map((item) => { return item.equipmentId; })
};

/** 提交按钮 */
const submitForm = () => {
  if (form.value.equipmentIds == null || form.value.equipmentIds.length == 0) {
    proxy?.$modal.msgWarning('请选择监控设备');
    return;
  }

  cameraMonitorPlanFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await updatecameraMonitorPlan(form.value).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');

      emit('success');
      emit('close');
    } else {
      proxy?.$modal.msgWarning('请检查输入项');
    }
  });
};

onMounted(() => {
  getInfo();
  getCameraList();
  getSelectedCameraList();
});
</script>
<style lang="scss" scoped>
:deep(.select-camera-form-item) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
  .el-form-item__content {
    height: calc(100% - 40px);
    display: flex;
    flex-direction: column;
  }
}
</style>
